# encoding: utf-8
"""
!/usr/bin/python3
@Author: Gao Shuo
@Time: 2019/3/22 17:14 
@ReadMe:
    Input: 
    Output: 
"""
import random
import math
import mesa

from mesa import Agent, Model
from mesa.time import RandomActivation
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector

# 全局变量
rate_marriage = 0.86
rate_birth = 0.011
rate_death = 0.009


# 计算满意度
def compute_satisfaction(model):
    agent_mood = [agent.satisfaction for agent in model.schedule.agents if agent.age > 60]
    per = sum(agent_mood) / model.num_agents
    return per

# 养老模型
class elderModel(Model):
    def __init__(self, N, width, height, inputDF):
        self.num_agents = N  # agent 个数
        self.running = True
        self.grid = MultiGrid(height, width, True)  # 画布 每个格子能有好几个agent
        self.schedule = RandomActivation(self)  # 每个agent的功能
        self.datacollector = DataCollector(
            model_reporters={"Satisfaction": compute_satisfaction}, #汇报满意度
            agent_reporters={"Satisfied": lambda a: a.satisfaction} #汇报每个人的满意程度
        )
        #         create agents
        self.inputDF = inputDF
        arr_family = inputDF['家庭'].unique()
        for family in arr_family:
            print('family:', family)
            selected = inputDF[inputDF['家庭'] == family]
            print(selected)
            # 每个家庭住在同一个地方
            x = random.randrange(self.grid.width)
            y = random.randrange(self.grid.height)

            #     成员  家庭  年龄  性别
            for row in range(selected.shape[0]):
                peopleID = selected.iat[row,0]
                familyID = selected.iat[row,1]
                age = selected.iat[row,2]
                gender = selected.iat[row,3]
                a = elderAgent(peopleID, self )
                # a = elderAgent(peopleID, self, familyID, age, gender)
                self.grid.place_agent(a, (x, y))  # 把agent随机放到某个位置

        # for i in range(self.num_agents):
        #     a = elderAgent(i, self)
        #     self.schedule.add(a)
        #     # Add the agent to a random grid cell
        #     x = random.randrange(self.grid.width)
        #     y = random.randrange(self.grid.height)
        #     self.grid.place_agent(a, (x, y)) #把agent随机放到某个位置
    def step(self):
        self.datacollector.collect(self)
        self.schedule.step()
        n_agents = self.num_agents
        born =int (n_agents * rate_birth)#新生儿
        for i in range(born):
            a = elderAgent(n_agents+1+i, self)


    def run_model(self, n):
        for i in range(n):
            self.step()
            print("step = ", step())
            """tax_period = step()%10
            if tax_period == 0
                return_tax(self, treasury)"""

class elderAgent(Agent):
    """ An agent with fixed initial wealth."""
    def __init__(self, unique_id, model):
        super().__init__(unique_id, model)
        self.id = unique_id
        self.satisfaction = random.randrange(100)/100 #初始满意度为0-1之间的小数
        self.wealth = random.randrange(100)/100 #初始财富值为0-1之间的小数
        self.age = random.randrange(90) #初始满意度为0-90
        x = random.randint(0, self.model.grid.width-1)
        y = random.randint(0, self.model.grid.height-1)
        print("X Y", x, "and", y) #初始坐标值
        # if self.model.grid.is_cell_empty([x,y]) == False:
        #     rich_pos = (x,y)
        #     rich_receivers = self.model.grid.get_cell_list_contents(rich_pos)
        #     rich = random.choice(rich_receivers)
        #     inequality_c = 4
        #     rich.wealth += inequality_c #在本单元格内的agent中，选取一个随机增加4点财富

    def calculate_satisfaction(self):
        self.satisfaction += self.wealth



    # 每一步
    def step(self):
        #self.move()
        # 年龄增加1
        self.age +=1
        # if self.age > 60:
        #     expenditure_c = 5
        #     self.daily_transactions(expenditure_c) #每天给邻居交钱
        #     self.donate_money()#有一半可能捐钱
        #     self.collect_tax()#每天查税
        #     self.project_reward(economy_scale,economy_scale)#给本区域内随机的人奖金
        #     #print("------------step------------")








